﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DataInfo;
using KenLib.BusinessManager;
using System.Collections.Generic;
using System.Drawing;
using XBLib.Dal.AdoDal;
using KenLib.Common;

public partial class frm_TraineeAcademicInfo : System.Web.UI.Page
{
    int count = 0;
    private const string ASCENDING = " ASC";
    private const string DESCENDING = " DESC";
    string strErr = "";
    学歴情報Manager magage = new 学歴情報Manager();
    string ID = "";
    private void resetData()
    {
        ddl_学歴区分.SelectedIndex = -1;
        ddl_開始時期月.SelectedIndex = -1;
        ddl_開始時期年.SelectedIndex = -1;
        ddl_終了時期月.SelectedIndex = -1;
        ddl_終了時期年.SelectedIndex = -1;
        txt_学校名.Text = "";
        txt_学校住所.Text = "";
        ddl_専攻区分.SelectedIndex = -1;
        ddl_全日夜間.SelectedIndex = -1;
        ddl_専攻系列コード.SelectedIndex = -1;
        txt_専攻学部.Text = "";
        txt_専攻学科.Text = "";
        txt_専攻内容.Text = "";
        txt_専門技術.Text = "";
        btn_登録.Text = "Nhập mới";
        grv_TraineeAcademicInfo.SelectedIndex = -1;
        ViewState["id_TraineeAcademicInfo"] = null;
    }
   
    private void loadDataIntoControl(学歴情報 obj)
    {
        ddl_学歴区分.SelectedValue = obj.学歴区分.ToString();
        ddl_開始時期月.SelectedValue = obj.開始時期.ToString("MM");
        ddl_開始時期年.SelectedValue = obj.開始時期.ToString("yyyy");
        ddl_終了時期月.SelectedValue = obj.終了時期.ToString("MM");
        ddl_終了時期年.SelectedValue = obj.終了時期.ToString("yyyy");
        txt_学校名.Text = obj.学校名;
        txt_学校住所.Text = obj.学校住所;
        ddl_専攻区分.SelectedValue = obj.専攻区分.ToString();
        if (obj.全日夜間 == null)
        {
            ddl_全日夜間.SelectedValue = "-1";
        }
        else
        {
            ddl_全日夜間.SelectedValue = Convert.ToBoolean(obj.全日夜間) ? "1" : "0";
        }
        ddl_専攻系列コード.SelectedValue = obj.専攻系列コード.ToString();
        txt_専攻学部.Text = obj.専攻学部;
        txt_専攻学科.Text = obj.専攻学科;
        txt_専攻内容.Text = obj.専攻内容;
        txt_専門技術.Text = obj.専門技術;
        btn_登録.Text = "Cập nhật";
        ViewState["id_TraineeAcademicInfo"] = obj.ID;
    }
    private void loadListEmpty()
    {
        //empty data

        grv_TraineeAcademicInfo.ShowFooter = false;
        grv_TraineeAcademicInfo.AllowSorting = false;

        List<学歴情報> ls = new List<学歴情報>();
        ls.Add(new 学歴情報());
        grv_TraineeAcademicInfo.DataSource = ls;
        grv_TraineeAcademicInfo.DataBind();
        grv_TraineeAcademicInfo.Rows[0].Cells.Clear();
        grv_TraineeAcademicInfo.Rows[0].Cells.Add(new TableCell());
        grv_TraineeAcademicInfo.Rows[0].Cells[0].ControlStyle.ForeColor = Color.Red;
        grv_TraineeAcademicInfo.Rows[0].Cells[0].ControlStyle.BorderColor = Color.Black;
        grv_TraineeAcademicInfo.Rows[0].Cells[0].ControlStyle.Font.Size = 12;
        grv_TraineeAcademicInfo.Rows[0].Cells[0].ColumnSpan = 5;
        grv_TraineeAcademicInfo.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
        grv_TraineeAcademicInfo.Rows[0].Cells[0].Text = "Không có kết quả về quá trình học tập của bạn.";


    }
    private void loadData(string sortExpression, string direction, string id)
    {
        string 学歴区分value = "(select value from dbo.fct_Split_With_ID(N'Trung học cơ sở,Trung học phổ thông,Cao đẳng,Cử nhân ,Thạc sĩ ,Tiến sĩ',',') where id=学歴区分) as 学歴区分Name";
        int iPagetotal = 0;
        List<学歴情報> lst = new GlobalManager().SelectDataInTableAndPaging<学歴情報>("学歴情報", 学歴区分value, "ID", sortExpression + " " + direction, "社員ID = " + id, grv_TraineeAcademicInfo.PageIndex + 1, grv_TraineeAcademicInfo.PageSize, ref iPagetotal);
        count = (int)Math.Ceiling(Convert.ToDecimal(iPagetotal) / grv_TraineeAcademicInfo.PageSize);
        hd_pageCount.Value = count.ToString();
        if (count < grv_TraineeAcademicInfo.PageIndex)
        {
            grv_TraineeAcademicInfo.PageIndex = count;
        }
        if (lst.Count > 0)
        {
            grv_TraineeAcademicInfo.ShowFooter = true;
            grv_TraineeAcademicInfo.AllowSorting = true;
            grv_TraineeAcademicInfo.DataSource = lst;
            grv_TraineeAcademicInfo.DataBind();

            loadDataIntoControl(lst[0]);
            grv_TraineeAcademicInfo.SelectedIndex = 0;
        }
        else
        {
            loadListEmpty();

        }

    }

    #region SORT
    private SortDirection GridViewSortDirection
    {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;
            return (SortDirection)ViewState["sortDirection"];
        }
        set { ViewState["sortDirection"] = value; }
    }
    private void AddSortImage(int columnIndex, GridViewRow headerRow)
    {
        string[] Texts = { "Giai đoạn", "Tên trường", "Thời gian bắt đầu", "Thời gian kết thúc" };
        string[] Sorts = { "学歴区分", "学校名", "開始時期", "終了時期" };
        // Create the sorting image based on the sort direction.
        LinkButton lblSort = new LinkButton();
        lblSort.ID = Sorts[columnIndex];
        if (GridViewSortDirection == SortDirection.Ascending)
        {
            lblSort.Text = Texts[columnIndex] + "▲";
            lblSort.ToolTip = "Ascending Order";
        }
        else
        {
            lblSort.Text = Texts[columnIndex] + "▼";
            lblSort.ToolTip = "Descending Order";
        }
        lblSort.CssClass = "aSort";
        lblSort.Click += new EventHandler(lblSort_Click);
        // Add the image to the appropriate header cell.

        headerRow.Cells[columnIndex].Text = "";
        headerRow.Cells[columnIndex].Controls.Add(lblSort);
    }
    void lblSort_Click(object sender, EventArgs e)
    {
        LinkButton lblSort = sender as LinkButton;
        string sortExpression = lblSort.ID;
        GridViewSortDirection = GridViewSortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
        loadData(sortExpression, GridViewSortDirection == SortDirection.Ascending ? ASCENDING : DESCENDING, ID);
    }
    private int GetSortColumnIndex()
    {
        foreach (DataControlField field in grv_TraineeAcademicInfo.Columns)
        {
            if (field.SortExpression == (string)ViewState["SortExpression"])
            {
                return grv_TraineeAcademicInfo.Columns.IndexOf(field);
            }
        }
        return -1;
    }
    #endregion
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["SessionLoginID"] == null)
        {
            Response.Redirect("frm_Menu.aspx");
        }
        grv_TraineeAcademicInfo.PageSize = Convert.ToInt32(ConfigurationManager.AppSettings["pagesize_child"].ToString());
       
        if (!IsPostBack)
        {
            ViewState["SortExpression"] = "ID";
            AppCode_Common.AddHistory(Page);
            
            //load year
            int startYear = Convert.ToInt32(ConfigurationManager.AppSettings["startYear"].ToString());
            for (int i = startYear; i <= DateTime.Now.Year; i++)
            {
                ddl_開始時期年.Items.Add(new ListItem(i.ToString(), i.ToString()));
                ddl_終了時期年.Items.Add(new ListItem(i.ToString(), i.ToString())); 
            }
            //load ddl
            List<専攻系列コード> ls = new GlobalManager().GetAllInfoInTable<専攻系列コード>("専攻系列コード", "ID", true);
            専攻系列コード ob = new 専攻系列コード();
            ob.ID = 0;
            ob.氏名 = "- Lựa chọn  -";
            ls.Insert(0, ob);
            ddl_専攻系列コード.DataSource = ls;
            ddl_専攻系列コード.DataBind();
            if (Request.QueryString["id"] != null)
            {
                loadData((string)ViewState["SortExpression"], ASCENDING, Request.QueryString["id"]);
              //  lbl_NameHeader.Text = AppCode_Common.GetUserName(Request.QueryString["id"]);

                
            }
            else if (Session["SessionLoginID"] != null)
            {
                loadData((string)ViewState["SortExpression"], ASCENDING, Session["SessionLoginID"].ToString());
              //  lbl_NameHeader.Text = AppCode_Common.GetUserName(Session["SessionLoginID"].ToString());
                resetData();

            }
           
        }
        if (Request.QueryString["id"] != null)
        {
            
            ID = Request.QueryString["id"];
        }
        else if (Session["SessionLoginID"] != null)
        {
            
            ID = Session["SessionLoginID"].ToString();

        }
        ((MasterPage)this.Master).changeTitle("THÔNG TIN VỀ QUÁ TRÌNH HỌC TẬP");

    }
    #region EVENT SORT
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            GridViewRow gvrPager = grv_TraineeAcademicInfo.FooterRow;
            DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
            grv_TraineeAcademicInfo.PageIndex = ddlPages.SelectedIndex;

            loadData((string)ViewState["SortExpression"], GridViewSortDirection == SortDirection.Ascending ? ASCENDING : DESCENDING,ID);
        }
        catch (LocalException ex)
        {
            strErr = ex.Message;
        }
        catch (Exception ex)
        {
            ExportFile.WriteErr(Session["id"] as string, Session["sessionManager"] as string, "", ex.Message, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
            strErr = ex.Message;
        }
        //finally
        //{
        //    if (strErr != "")
        //        Response.Redirect(ConfigurationSettings.AppSettings["PAGE_ERROR"] + "?err=" + Server.UrlEncode(strErr), false);
        //}
    }
    protected void grv_TraineeAcademicInfo_DataBound(object sender, EventArgs e)
    {
        try
        {
            GridViewRow gvrPager = grv_TraineeAcademicInfo.FooterRow;
            if (gvrPager == null) return;
            DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
            Label lblPageCount = (Label)gvrPager.Cells[0].FindControl("lblPageCount");
            if (ddlPages != null)
            {
                for (int i = 0; i < count; i++)
                {
                    int intPageNumber = i + 1;
                    ListItem lstItem = new ListItem(intPageNumber.ToString());
                    if (i == grv_TraineeAcademicInfo.PageIndex)
                        lstItem.Selected = true;
                    ddlPages.Items.Add(lstItem);
                }
            }

            if (lblPageCount != null)
                lblPageCount.Text = count.ToString();
        }
        catch (LocalException ex)
        {
            strErr = ex.Message;
        }
        catch (Exception ex)
        {
            ExportFile.WriteErr(Session["id"] as string, Session["sessionManager"] as string, "", ex.Message, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
            strErr = ex.Message;
        }
        //finally
        //{
        //    if (strErr != "")
        //        Response.Redirect(ConfigurationSettings.AppSettings["PAGE_ERROR"] + "?err=" + Server.UrlEncode(strErr), false);
        //}
    }
    protected void grv_TraineeAcademicInfo_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "SELECT")
        {
            List<学歴情報> ls = new GlobalManager().GetInfoInTableByValue<学歴情報>("学歴情報", "ID", e.CommandArgument.ToString(), false);
            loadDataIntoControl(ls[0]);
            ViewState["id_TraineeAcademicInfo"] = ls[0].ID;
            btn_登録.Text = "Cập nhật";
        }
        else if (e.CommandName == "del")
        { 
            //delete
            if (magage.Delete(Convert.ToInt32(e.CommandArgument.ToString())) > 0)
            {
                loadData((string)ViewState["SortExpression"], ASCENDING, ID);
                resetData();
            }
        }
        else if (e.CommandName == "Page")
        {
            int pageCount = Convert.ToInt32(hd_pageCount.Value);
            int intCurIndex = grv_TraineeAcademicInfo.PageIndex;
            switch (e.CommandArgument.ToString().ToLower())
            {
                case "first":
                    grv_TraineeAcademicInfo.PageIndex = 0;

                    break;
                case "prev":
                    if (intCurIndex > 0)
                        grv_TraineeAcademicInfo.PageIndex = intCurIndex - 1;
                    break;
                case "next":
                    if (intCurIndex < pageCount - 1)
                        grv_TraineeAcademicInfo.PageIndex = intCurIndex + 1;
                    break;
                case "last":
                    grv_TraineeAcademicInfo.PageIndex = pageCount - 1;
                    break;
            }

            loadData((string)ViewState["SortExpression"], GridViewSortDirection == SortDirection.Ascending ? ASCENDING : DESCENDING,ID);
            GridViewRow gvrPager = grv_TraineeAcademicInfo.FooterRow;
            if (gvrPager == null) return;
            DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
            ddlPages.SelectedIndex = grv_TraineeAcademicInfo.PageIndex;
        }
    }
    protected void grv_TraineeAcademicInfo_RowCreated(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                int sortColumnIndex = GetSortColumnIndex();
                if (sortColumnIndex >= 0)
                {
                    AddSortImage(sortColumnIndex, e.Row);
                }

            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {

                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    if (i == 0)
                        e.Row.Cells[i].ColumnSpan = e.Row.Cells.Count;
                    else
                        e.Row.Cells[i].Visible = false;

                }
            }
        }
        catch (LocalException ex)
        {
            strErr = ex.Message;
        }
        catch (Exception ex)
        {
            ExportFile.WriteErr(Session["id"] as string, Session["sessionManager"] as string, "", ex.Message, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
            strErr = ex.Message;
        }
        //finally
        //{
        //    if (strErr != "")
        //        Response.Redirect(ConfigurationSettings.AppSettings["PAGE_ERROR"] + "?err=" + Server.UrlEncode(strErr), false);
        //}
    }
    protected void grv_TraineeAcademicInfo_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            string sortExpression = e.SortExpression;
            ViewState["SortExpression"] = sortExpression;

            if (GridViewSortDirection == SortDirection.Ascending)
            {
                GridViewSortDirection = SortDirection.Descending;
                loadData(sortExpression, DESCENDING,ID);
            }
            else
            {
                GridViewSortDirection = SortDirection.Ascending;
                loadData(sortExpression, ASCENDING, ID);
            }
        }
        catch (LocalException ex)
        {
            strErr = ex.Message;
        }
        catch (Exception ex)
        {
            ExportFile.WriteErr(Session["id"] as string, Session["sessionManager"] as string, "", ex.Message, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
            strErr = ex.Message;
        }
        //finally
        //{
        //    if (strErr != "")
        //        Response.Redirect(ConfigurationSettings.AppSettings["PAGE_ERROR"] + "?err=" + Server.UrlEncode(strErr), false);
        //}
    }
    #endregion
    protected void btn_登録_Click(object sender, EventArgs e)
    {
        try
        {
            //check validation
           if (ddl_学歴区分.SelectedValue == "")
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "show", "alert('Hãy chọn giai đoạn.')", true);
                ddl_学歴区分.Focus();
                return;
            }
            if (ddl_開始時期月.SelectedValue == "" || ddl_開始時期年.SelectedValue == "")
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "show", "alert('Hãy chọn thời gian bắt đầu.')", true);
                if (ddl_開始時期月.SelectedValue == "")
                {
                    ddl_開始時期月.Focus();
                }
                else if (ddl_開始時期年.SelectedValue == "")
                {
                    ddl_開始時期年.Focus();
                }
                return;
            }
           
            if (ddl_終了時期月.SelectedValue == "" || ddl_終了時期年.SelectedValue == "")
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "show", "alert('Hãy chọn thời gian kết thúc.')", true);
                if (ddl_終了時期月.SelectedValue == "")
                {
                    ddl_終了時期月.Focus();
                }
                else if (ddl_終了時期年.SelectedValue == "")
                {
                    ddl_終了時期年.Focus();
                }
                return;
            }
            if (DateTime.ParseExact(ddl_終了時期年.SelectedValue + ddl_終了時期月.SelectedValue + "01", "yyyyMMdd", null) <= DateTime.ParseExact(ddl_開始時期年.SelectedValue + ddl_開始時期月.SelectedValue + "01", "yyyyMMdd", null))
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "show", "alert('Thời gian bắt đầu và kết thúc không hợp lý. hãy chọn lại')", true);
                ddl_終了時期年.Focus();
                return;
            }
            if (txt_学校名.Text == "")
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "show", "alert('Hãy nhập tên trường.')", true);
                txt_学校名.Focus();
                return;
            }

          
           
            //insert - update

            学歴情報 obj = new 学歴情報();
            obj.廃止区分 = 0;//waiting
            obj.開始時期=   DateTime.ParseExact(ddl_開始時期年.SelectedValue + ddl_開始時期月.SelectedValue + "01", "yyyyMMdd", null); 
            obj.学校住所=txt_学校住所.Text;
            obj.学校名=txt_学校名.Text;
            obj.学歴区分= Convert.ToInt32(ddl_学歴区分.SelectedValue);
            obj.社員ID=Convert.ToInt32(ID);
            obj.終了時期=DateTime.ParseExact(ddl_終了時期年.SelectedValue + ddl_終了時期月.SelectedValue + "01", "yyyyMMdd", null); 
            obj.専攻学科=txt_専攻学科.Text;
            obj.専攻学部=txt_専攻学部.Text;
            obj.専攻区分 = Convert.ToInt32(ddl_専攻区分.SelectedValue);
            obj.専攻系列コード =Convert.ToInt32(ddl_専攻系列コード.SelectedValue);
            obj.専攻内容=txt_専攻内容.Text;
            obj.専門技術=txt_専門技術.Text;
            if(ddl_全日夜間.SelectedValue == "-1")
                obj.全日夜間 =null;
            else
                obj.全日夜間 =  (ddl_全日夜間.SelectedValue == "1");
           
            obj.区分=0;
            obj.専攻系列=ddl_専攻系列コード.SelectedItem.Text;
            obj.担当教授名="";

            if (ViewState["id_TraineeAcademicInfo"] != null)
            {
                obj.ID = Convert.ToInt32(ViewState["id_TraineeAcademicInfo"].ToString());
                if (magage.Update(obj) > 0)
                {
                   // ScriptManager.RegisterStartupScript(this, this.GetType(), "show", "alert('Cập nhật thông tin học tập thành công')", true);
                    loadData((string)ViewState["SortExpression"], ASCENDING,ID);
                    resetData();
                    ViewState["id_TraineeAcademicInfo"] = null;
                   

                }
            }
            else
            {
                if (magage.Insert(obj) > 0)
                {
                   // ScriptManager.RegisterStartupScript(this, this.GetType(), "show", "alert('Thêm mới thông tin học tập thành công')", true);
                    loadData((string)ViewState["SortExpression"], ASCENDING, ID);
                    resetData();
                }

            }

        }
        catch (LocalException ex)
        {
            strErr = ex.Message;
        }
        catch (Exception ex)
        {
            ExportFile.WriteErr(Session["id"] as string, Session["sessionManager"] as string, "", ex.Message, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
            strErr = ex.Message;
        }
        //finally
        //{
        //    if (strErr != "")
        //        Response.Redirect(ConfigurationSettings.AppSettings["PAGE_ERROR"] + "?err=" + Server.UrlEncode(strErr), false);
        //}


    }
    protected void btn_リセット_Click(object sender, EventArgs e)
    {
        resetData();
    }
    protected void btn_次_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["id"] != null)
        {
            Response.Redirect("frm_TraineeWorkedCompInfo.aspx?id=" + Request.QueryString["id"]);
        }
        else if (Session["SessionLoginID"] != null)
        {
            Response.Redirect("frm_TraineeWorkedCompInfo.aspx");
        }
    }
    protected void btn_OK_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["id"] != null)
        {
            string pageBack = AppCode_Common.getHistory(Page);
            Response.Redirect(pageBack);
        }
        else if (Session["SessionLoginID"] != null)
        {
            Response.Redirect("frm_Menu.aspx?page=TraineeAcademicInfo");
        }
    }
}
